import React, { Component } from 'react'
import { Form, Input, Button, Tabs, message } from 'antd'
import { LoginInner } from './style'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { registerApi, loginApi } from '../../api/user'
import md5 from 'js-md5'

export default class Login extends Component {
  registerFormRef = React.createRef()
  loginFormRef = React.createRef()

  state = {
    buttonLoading: false,
    activeKey: 'login'
  }

  // 校验用户密码格式
  validatePassword = (p) => {
    return /^(?=.*[a-z])(?=.*[A-Z])(?=.*[\d])[a-zA-Z\d]{6,}$/.test(p)
  }

  // 点击注册
  register = ({ username, password }) => {
    const data = { username, password: md5(password) }
    if (!this.validatePassword(password)) {
      return message.warning('密码必须包含字母、数字、大小写且不少于6位')
    }
    this.setState({ buttonLoading: true })
    registerApi(data).then((res) => {
      if (res.code === 200) {
        message.success('注册成功')
        this.registerFormRef.current.resetFields()
        this.props.history.push('/')
      } else {
        message.error(res.msg || '登录失败')
      }
      this.setState({ buttonLoading: false })
    })
  }

  // 点击登录
  login = ({ username, password }) => {
    const data = { username, password: md5(password) }
    this.setState({ buttonLoading: true })
    loginApi(data).then((res) => {
      if (res.code === 200) {
        message.success('登录成功')
        this.loginFormRef.current.resetFields()
        this.props.history.push('/')
        console.log('user', res.data)
      } else {
        message.error(res.msg || '登录失败')
      }
      this.setState({ buttonLoading: false })
    })
  }

  changeTab = (key) => {
    this.setState({
      activeKey: key
    })
  }

  render() {
    const { buttonLoading, activeKey } = this.state
    return (
      <LoginInner>
        <div className="center">
          <div className="title">
            <span className="logo-img"></span>
            <span className="logo-text"></span>
          </div>
          <div className="login-main">
            <Tabs
              defaultActiveKey="login"
              activeKey={activeKey}
              className="tabs"
              onTabClick={this.changeTab}
            >
              <Tabs.TabPane tab="用户登录" key="login">
                <Form
                  labelCol={{ span: 0 }}
                  wrapperCol={{ span: 24 }}
                  ref={this.loginFormRef}
                  onFinish={this.login}
                >
                  <Form.Item
                    name="username"
                    rules={[{ required: true, message: '请输入用户名' }]}
                  >
                    <Input
                      size="large"
                      prefix={<UserOutlined />}
                      placeholder="请输入用户名"
                    />
                  </Form.Item>
                  <Form.Item
                    name="password"
                    rules={[{ required: true, message: '请输入密码' }]}
                  >
                    <Input.Password
                      size="large"
                      prefix={<LockOutlined />}
                      placeholder="请输入密码"
                    />
                  </Form.Item>
                  <Form.Item wrapperCol={{ offset: 0, span: 24 }}>
                    <Button
                      type="primary"
                      size="large"
                      block={true}
                      htmlType="submit"
                      loading={buttonLoading}
                    >
                      登录
                    </Button>
                  </Form.Item>
                </Form>
              </Tabs.TabPane>
              <Tabs.TabPane tab="用户注册" key="register">
                <Form
                  name="userRegister"
                  labelCol={{ span: 0 }}
                  wrapperCol={{ span: 24 }}
                  ref={this.registerFormRef}
                  onFinish={this.register}
                >
                  <Form.Item
                    name="username"
                    rules={[{ required: true, message: '请输入用户名' }]}
                  >
                    <Input
                      size="large"
                      prefix={<UserOutlined />}
                      placeholder="请输入用户名"
                    />
                  </Form.Item>
                  <Form.Item
                    name="password"
                    rules={[{ required: true, message: '请输入密码' }]}
                  >
                    <Input.Password
                      size="large"
                      prefix={<LockOutlined />}
                      placeholder="请输入密码"
                    />
                  </Form.Item>
                  <Form.Item
                    name="confirm"
                    rules={[
                      { required: true, message: '请输入密码' },
                      ({ getFieldValue }) => {
                        return {
                          validator(_, value) {
                            if (!value || getFieldValue('password') === value) {
                              return Promise.resolve()
                            }
                            return Promise.reject('两次密码不一致')
                          }
                        }
                      }
                    ]}
                  >
                    <Input.Password
                      size="large"
                      prefix={<LockOutlined />}
                      placeholder="请确认密码"
                    />
                  </Form.Item>
                  <Form.Item wrapperCol={{ offset: 0, span: 24 }}>
                    <Button
                      type="primary"
                      size="large"
                      block={true}
                      htmlType="submit"
                      loading={buttonLoading}
                    >
                      注册
                    </Button>
                  </Form.Item>
                </Form>
              </Tabs.TabPane>
            </Tabs>
          </div>
        </div>
      </LoginInner>
    )
  }
}
